# 需求1：写一个类视图，提供一下1个接口
# 1.获取所有的图书数据get / books /


# 最基础版本
class BookListView(APIView):
    def get(self, request):
        books = BookInfo.objects.all()
        serializer = BookInfoSerializer(books, many=True)
        return Response(serializer.data)

        # GenericAPIView版本


class BookGet(GenericAPIView):
    queyset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get(self, request):
        books = self.get_queryset()
        serializer = self.get_serializer(books, many=True)
        return Response(serializer.data)

        # Mixin扩展类版本


class BookListView(ListModelMixin,
                   GenericAPIView):
    serializer_class = BookInfoSerializer


    queryset = BookInfo.objects.all()


    def get(self, request):
        return self.list(request)


# 最简单版本
class BookListView(ListAPIView):
    queryset = BookInfo.object.all()
    serializer_class = BookInfoSerializer

# 需求2：写一个类视图，提供以下两个接口
# 1.
# 获取指定的图书数据
# get / books / (?P < pk >\d +) /
# 2.
# 修改指定的图书数据
# put / books / (?P < pk >\d +) /
# 最基础版本
class BookRetrieveUpdateView(APIView):
    def get(self, request, pk):
        try:
            book = BookInfo.objects.get('pk')
        except BookInfo.DoesNotExist:
            raise Http404
        serializer = BookInfoSerializer(book)
        return Response(serializer.data)

    def put(self, request, pk):
        try:
            book = BookInfo.objects.get('pk')
        except BookInfo.DoesNotExist:
            raise Http404
        serializer = BookInfoSerializer(book, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

# GenericAPIView
class BookRetrieveUpdateView(GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get(self, request, pk):
        book = self.get_object()

        serializer = self.get_serializer(book)
        return Response(serializer.data)

    def put(self, request, pk):
        book = self.get_object()

        serializer = self.get_serializer(book, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

# Mixin版本
class BookRetrieveUpdateView(RetrieveModelMixin,
                             UpdateModelMixin,
                             GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get(self, request, pk):
        return self.retrieve(request)

    def put(self, request, pk):
        return self.update(request)

# 最简单版本
class BookRetrieveUpdateView(RetrieveUpdateAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer